package net.tngou.iask.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.tngou.iask.jdbc.PageUtil;
import net.tngou.iask.jdbc.QueryHelper;
import net.tngou.iask.pojo.Answer;

/**
 * 消息
 * @author tngou@tngou.net
 *
 */
public class MsgsDao extends BaseDao {

	
	/**
	 * 取得私信
	 * @param user
	 * @param friend
	 * @param page
	 * @param size
	 * @return
	 */
	public PageUtil getPage(long user,long friend,int page,int size) {
		List<Map<String, Object>> list=new ArrayList<>();
		int total=0;
		Object[] params={user,friend};
		String total_sql="SELECT COUNT(*) FROM `iask_msgs` WHERE user=? AND friend=? ";
		String sql ="SELECT msg.*,user.name,user.avatar FROM (SELECT * FROM `iask_msgs` WHERE user=? AND friend=? AND type=0 ORDER BY `id` DESC) msg LEFT OUTER JOIN `iask_user` user ON user.id=msg.sender ORDER BY msg.id DESC ";
		total=(int) QueryHelper.stat(total_sql, params);
		list=QueryHelper.query_page(sql, page, size, params);
		
		return new PageUtil(list, page, size, total);
		
	}
	
	/**
	 * 取得用户未读消息
	 * @param user
	 * @return
	 */
	public List<Map<String, Object>> getList(long user) {
		String sql ="SELECT msg.*,user.name,user.avatar FROM (SELECT * FROM `iask_msgs` WHERE user=? AND receiver=? AND isread=0 AND type=0 ORDER BY `id` DESC) msg LEFT OUTER JOIN `iask_user` user ON user.id=msg.sender ORDER BY msg.id DESC ";
	   return QueryHelper.query(sql, user,user);
	}

	/**
	 * 设置已读
	 * @param user
	 * @param friend
	 */
	public void setRead(long user, long friend) {
		String sql ="UPDATE `iask_msgs` SET `isread`=1 WHERE user=? AND friend=? AND isread=0";
		QueryHelper.update(sql, user,friend);
	}
}
